import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  ScrollView,
  Image,
  TouchableOpacity,
  Alert,
  Dimensions,
  StyleSheet,
  ActivityIndicator,
  SafeAreaView,
  StatusBar,
  Platform,
} from 'react-native';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { getPostDetail, toggleLikePost, toggleFavoritePost } from '../services/postService';
import { PostDetailVO } from '../../types/post';

const { width } = Dimensions.get('window');

/**
 * 帖子详情页面
 * 展示帖子的完整内容，包括用户信息、内容、图片、点赞收藏等功能
 */
export default function PostDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const [postDetail, setPostDetail] = useState<PostDetailVO | null>(null);
  const [loading, setLoading] = useState(true);
  const [isLiking, setIsLiking] = useState(false);
  const [isFavoriting, setIsFavoriting] = useState(false);

  // 获取帖子详情数据
  const fetchPostDetail = async () => {
    try {
      setLoading(true);
      const response = await getPostDetail(Number(id));
      setPostDetail(response.data);
    } catch (error: any) {
      console.error('获取帖子详情失败:', error);
      Alert.alert('错误', error.message || '获取帖子详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理点赞
  const handleLike = async () => {
    if (!postDetail || isLiking) return;
    
    try {
      setIsLiking(true);
      await toggleLikePost(postDetail.id);
      
      // 更新本地状态
      setPostDetail(prev => prev ? {
        ...prev,
        hasThumb: !prev.hasThumb,
        thumbNum: prev.hasThumb ? prev.thumbNum - 1 : prev.thumbNum + 1
      } : null);
    } catch (error: any) {
      console.error('点赞操作失败:', error);
      Alert.alert('错误', error.message || '点赞操作失败');
    } finally {
      setIsLiking(false);
    }
  };

  // 处理收藏
  const handleFavorite = async () => {
    if (!postDetail || isFavoriting) return;
    
    try {
      setIsFavoriting(true);
      await toggleFavoritePost(postDetail.id);
      
      // 更新本地状态
      setPostDetail(prev => prev ? {
        ...prev,
        hasFavour: !prev.hasFavour,
        favourNum: prev.hasFavour ? prev.favourNum - 1 : prev.favourNum + 1
      } : null);
    } catch (error: any) {
      console.error('收藏操作失败:', error);
      Alert.alert('错误', error.message || '收藏操作失败');
    } finally {
      setIsFavoriting(false);
    }
  };

  // 显示功能开发中提醒
  const showFeatureInDevelopment = (featureName: string) => {
    Alert.alert('提示', `${featureName}功能正在开发中，敬请期待！`);
  };

  // 格式化时间
  const formatTime = (timeString: string) => {
    const date = new Date(timeString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else if (days < 30) {
      return `${days}天前`;
    } else {
      return date.toLocaleDateString();
    }
  };

  useEffect(() => {
    if (id) {
      fetchPostDetail();
    }
  }, [id]);

  if (loading) {
    return (
      <View className="flex-1 bg-white" style={{ paddingTop: insets.top }}>
        <StatusBar 
          barStyle="dark-content" 
          backgroundColor="#FFFFFF" 
          translucent={Platform.OS === 'android'}
        />
        <View className="flex-1 justify-center items-center">
          <ActivityIndicator size="large" color="#007AFF" />
          <Text className="mt-2 text-gray-600">加载中...</Text>
        </View>
      </View>
    );
  }

  if (!postDetail) {
    return (
      <View className="flex-1 bg-white" style={{ paddingTop: insets.top }}>
        <StatusBar 
          barStyle="dark-content" 
          backgroundColor="#FFFFFF" 
          translucent={Platform.OS === 'android'}
        />
        <View className="flex-1 justify-center items-center">
          <Text className="text-gray-600">帖子不存在或已被删除</Text>
          <TouchableOpacity 
            className="mt-4 px-6 py-2 bg-blue-500 rounded-lg"
            onPress={() => router.back()}
          >
            <Text className="text-white font-medium">返回</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }

  return (
    <View className="flex-1 bg-white" style={{ paddingTop: insets.top }}>
      <StatusBar 
        barStyle="dark-content" 
        backgroundColor="#FFFFFF" 
        translucent={Platform.OS === 'android'}
      />
      
      {/* 顶部导航栏 */}
      <View className="flex-row items-center justify-between px-4 py-3 bg-white border-b border-gray-200">
        <TouchableOpacity onPress={() => router.back()}>
          <Ionicons name="arrow-back" size={24} color="#000" />
        </TouchableOpacity>
        <Text className="text-lg font-semibold">帖子详情</Text>
        <TouchableOpacity onPress={() => showFeatureInDevelopment('分享')}>
          <Ionicons name="share-outline" size={24} color="#000" />
        </TouchableOpacity>
      </View>

      <ScrollView 
        className="flex-1" 
        showsVerticalScrollIndicator={false}
        contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 10) }}
      >
        {/* 用户信息区域 */}
        <View className="flex-row items-center justify-between p-4 bg-white">
          <View className="flex-row items-center flex-1">
            <Image
              source={{ 
                uri: postDetail.user.userAvatar || 'https://via.placeholder.com/40x40?text=User' 
              }}
              className="w-12 h-12 rounded-full"
            />
            <View className="ml-3 flex-1">
              <Text className="text-base font-semibold text-gray-900">
                {postDetail.user.nickname}
              </Text>
              <Text className="text-sm text-gray-600">
                {postDetail.user.major} • {postDetail.user.grade}
              </Text>
            </View>
          </View>
          <TouchableOpacity 
            className="px-4 py-2 bg-blue-500 rounded-full"
            onPress={() => showFeatureInDevelopment('关注')}
          >
            <Text className="text-white text-sm font-medium">+ 关注</Text>
          </TouchableOpacity>
        </View>

        {/* 标签区域 */}
        {postDetail.tags && postDetail.tags.length > 0 && (
          <View className="flex-row flex-wrap px-4 pb-2">
            {postDetail.tags.map((tag, index) => (
              <View key={index} className="bg-blue-100 px-3 py-1 rounded-full mr-2 mb-2">
                <Text className="text-blue-600 text-sm">{tag}</Text>
              </View>
            ))}
          </View>
        )}

        {/* 帖子内容 */}
        <View className="px-4 py-2">
          <Text className="text-base text-gray-900 leading-6">
            {postDetail.content}
          </Text>
        </View>

        {/* 图片展示 */}
        {postDetail.images && postDetail.images.length > 0 && (
          <View className="px-4 py-2">
            <View className="flex-row flex-wrap">
              {postDetail.images.map((image, index) => (
                <View key={index} className="mb-2 mr-2">
                  <Image
                    source={{ uri: image }}
                    style={{
                      width: postDetail.images.length === 1 ? width - 32 : (width - 48) / 2,
                      height: 200,
                    }}
                    className="rounded-lg"
                    resizeMode="cover"
                  />
                </View>
              ))}
            </View>
          </View>
        )}

        {/* 发布时间 */}
        <View className="px-4 py-2">
          <Text className="text-sm text-gray-500">
            发布于 {formatTime(postDetail.createTime)}
          </Text>
        </View>
      </ScrollView>

      {/* 底部操作栏 */}
      <View 
        className="flex-row items-center justify-around py-3 px-4 bg-white border-t border-gray-200"
        style={{ paddingBottom: Math.max(insets.bottom, 10) }}
      >
        {/* 点赞按钮 */}
        <TouchableOpacity 
          className="flex-row items-center"
          onPress={handleLike}
          disabled={isLiking}
        >
          <Ionicons 
            name={postDetail.hasThumb ? "heart" : "heart-outline"} 
            size={24} 
            color={postDetail.hasThumb ? "#FF4757" : "#666"} 
          />
          <Text className={`ml-1 text-sm ${postDetail.hasThumb ? 'text-red-500' : 'text-gray-600'}`}>
            {postDetail.thumbNum}
          </Text>
        </TouchableOpacity>

        {/* 评论按钮 */}
        <TouchableOpacity 
          className="flex-row items-center"
          onPress={() => showFeatureInDevelopment('评论')}
        >
          <Ionicons name="chatbubble-outline" size={24} color="#666" />
          <Text className="ml-1 text-sm text-gray-600">{postDetail.commentNum}</Text>
        </TouchableOpacity>

        {/* 收藏按钮 */}
        <TouchableOpacity 
          className="flex-row items-center"
          onPress={handleFavorite}
          disabled={isFavoriting}
        >
          <Ionicons 
            name={postDetail.hasFavour ? "bookmark" : "bookmark-outline"} 
            size={24} 
            color={postDetail.hasFavour ? "#007AFF" : "#666"} 
          />
          <Text className={`ml-1 text-sm ${postDetail.hasFavour ? 'text-blue-500' : 'text-gray-600'}`}>
            {postDetail.favourNum}
          </Text>
        </TouchableOpacity>

        {/* 分享按钮 */}
        <TouchableOpacity 
          className="flex-row items-center"
          onPress={() => showFeatureInDevelopment('分享')}
        >
          <Ionicons name="share-outline" size={24} color="#666" />
          <Text className="ml-1 text-sm text-gray-600">分享</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
} 